const rewardAd = require('../../utils/rewardAd.js');
const api = require('../../utils/api.js');
const app = getApp()
Page({
    data: {
        userName: "微信用户", // 用户名称
        signDays: 1, // 连续签到天数
        points: 0, // 积分余额
        isSigned: false, // 今日是否已签到
        remainingTasks: 2, // 剩余待完成任务数
        taskList: [
            {
                id: 1,
                name: "每日登录",
                desc: "每日首次登录即可获得积分",
                icon: "/assets/icons/login.png",
                completed: true,
                points: 5
            },
            {
                id: 2,
                name: "微信好友助力",
                desc: "每天2次分享免费获取积分",
                icon: "/assets/icons/friend.png",
                completed: false,
                maxTimes: 2,
                currentTimes: 0,
                points: 10
            },
            {
                id: 3,
                name: "观看激励视频",
                desc: "每天2次轻松获取免费积分",
                icon: "/assets/icons/video.png",
                completed: false,
                maxTimes: 2,
                currentTimes: 0,
                points: 5
            }
        ]
    },

    // 本地存储相关常量
    STORAGE_KEYS: {
        TASK_DATA: 'task_data',
        USER_POINTS: 'user_points',
        SIGN_DATA: 'sign_data',
        LAST_UPDATE: 'task_last_update'
    },
    onShowAd() {
      const userId = wx.getStorageSync('userId');
      rewardAd.showRewardAd();
    },
    onLoad: function (options) {
        console.log('任务页面加载');
        this.initTaskData();
        this.initRewardAd()
    },
    unlockContent() {
      const userId = wx.getStorageSync('userId');
      request(api.videoAd + '?user_id=' + userId, 'GET')
        .then(res => {
          wx.showToast({
            title: '奖励已发放'
          });
        })
        .catch(err => {
          console.error('发放奖励失败', err);
        });
    },
    initRewardAd() {
      app.getConfig('videoAd', res => {
        if (res.is_public) {
          this.setData({
            showVideoAd: true
          })
          rewardAd.initRewardAd(res.value, (isFinished) => {
            if (isFinished) {
              this.unlockContent();
            } else {
              wx.showToast({
                title: '请完整观看视频才能领取奖励',
                icon: 'none'
              });
            }
          });
        }
      })
    },
    // 初始化任务数据
    initTaskData() {
        // 检查是否需要重置每日任务
        this.checkDailyReset();

        // 加载本地数据
        this.loadLocalData();

        // 更新显示
        this.updateTaskDisplay();

        
    },

    // 检查每日重置
    checkDailyReset() {
        const today = new Date().toDateString();
        const lastUpdate = wx.getStorageSync(this.STORAGE_KEYS.LAST_UPDATE);

        console.log('检查每日重置 - 今天:', today, '上次更新:', lastUpdate);

        if (lastUpdate !== today) {
            console.log('执行每日重置');
            // 重置每日任务
            this.resetDailyTasks();
            // 更新日期
            wx.setStorageSync(this.STORAGE_KEYS.LAST_UPDATE, today);
        }
    },

    // 重置每日任务
    resetDailyTasks() {
        const defaultTaskList = [
            {
                id: 1,
                name: "每日登录",
                desc: "每日首次登录即可获得积分",
                icon: "/assets/icons/login.png",
                completed: true, // 登录即完成
                points: 5
            },
            {
                id: 2,
                name: "微信好友助力",
                desc: "每天2次分享免费获取积分",
                icon: "/assets/icons/friend.png",
                completed: false,
                maxTimes: 2,
                currentTimes: 0,
                points: 10
            },
            {
                id: 3,
                name: "观看激励视频",
                desc: "每天2次轻松获取免费积分",
                icon: "/assets/icons/video.png",
                completed: false,
                maxTimes: 2,
                currentTimes: 0,
                points: 5
            }
        ];

        // 保存重置后的任务数据
        wx.setStorageSync(this.STORAGE_KEYS.TASK_DATA, defaultTaskList);

        // 重置签到状态
        const signData = {
            isSigned: false,
            signDays: this.getSignDays() // 保持连续签到天数
        };
        wx.setStorageSync(this.STORAGE_KEYS.SIGN_DATA, signData);

        console.log('每日任务已重置');
    },

    // 加载本地数据
    loadLocalData() {
        // 加载任务数据
        const savedTaskList = wx.getStorageSync(this.STORAGE_KEYS.TASK_DATA);
        if (savedTaskList && savedTaskList.length > 0) {
            this.setData({ taskList: savedTaskList });
        }

        // 加载积分数据
        const savedPoints = wx.getStorageSync(this.STORAGE_KEYS.USER_POINTS);
        if (savedPoints !== undefined && savedPoints !== null) {
            this.setData({ points: savedPoints });
        }

        // 加载签到数据
        const savedSignData = wx.getStorageSync(this.STORAGE_KEYS.SIGN_DATA);
        if (savedSignData) {
            this.setData({
                isSigned: savedSignData.isSigned || false,
                signDays: savedSignData.signDays || 1
            });
        }

        console.log('本地数据加载完成:', {
            points: this.data.points,
            isSigned: this.data.isSigned,
            taskList: this.data.taskList
        });
    },

    // 保存任务数据到本地
    saveTaskData() {
        wx.setStorageSync(this.STORAGE_KEYS.TASK_DATA, this.data.taskList);
        console.log('任务数据已保存到本地');
    },

    // 保存积分数据到本地
    savePointsData() {
        wx.setStorageSync(this.STORAGE_KEYS.USER_POINTS, this.data.points);
        console.log('积分数据已保存:', this.data.points);
    },

    // 保存签到数据到本地
    saveSignData() {
        const signData = {
            isSigned: this.data.isSigned,
            signDays: this.data.signDays
        };
        wx.setStorageSync(this.STORAGE_KEYS.SIGN_DATA, signData);
        console.log('签到数据已保存:', signData);
    },

    // 获取连续签到天数
    getSignDays() {
        const savedSignData = wx.getStorageSync(this.STORAGE_KEYS.SIGN_DATA);
        return savedSignData ? (savedSignData.signDays || 1) : 1;
    },

    // 更新任务显示
    updateTaskDisplay() {
        const remainingTasks = this.data.taskList.filter(task => !task.completed).length;
        this.setData({ remainingTasks });
    },

    // 处理分享按钮点击
    handleShare() {
        const taskList = [...this.data.taskList];
        const shareTask = taskList.find(task => task.id === 2);

        if (!shareTask) {
            wx.showToast({
                title: '任务不存在',
                icon: 'none'
            });
            return;
        }

        if (shareTask.completed) {
            wx.showToast({
                title: '今日分享任务已完成',
                icon: 'none'
            });
            return;
        }

        if (shareTask.currentTimes >= shareTask.maxTimes) {
            wx.showToast({
                title: '今日分享次数已用完',
                icon: 'none'
            });
            return;
        }

        // 模拟分享操作
        wx.showLoading({
            title: '分享中...',
        });

        setTimeout(() => {
            wx.hideLoading();

            // 更新分享次数
            shareTask.currentTimes += 1;

            // 检查是否完成任务
            if (shareTask.currentTimes >= shareTask.maxTimes) {
                shareTask.completed = true;
            }

            // 增加积分
            const earnedPoints = shareTask.points / shareTask.maxTimes; // 每次分享获得的积分
            const newPoints = this.data.points + earnedPoints;

            // 更新数据
            this.setData({
                taskList,
                points: newPoints
            });

            // 保存到本地
            this.saveTaskData();
            this.savePointsData();
            this.updateTaskDisplay();

            wx.showToast({
                title: `分享成功 +${earnedPoints}积分`,
                icon: 'success'
            });

            console.log('分享任务完成:', {
                currentTimes: shareTask.currentTimes,
                completed: shareTask.completed,
                points: newPoints
            });
        }, 1000);
    },

    // 处理观看视频按钮点击
    handleWatchVideo() {
        const taskList = [...this.data.taskList];
        const videoTask = taskList.find(task => task.id === 3);

        if (!videoTask) {
            wx.showToast({
                title: '任务不存在',
                icon: 'none'
            });
            return;
        }

        if (videoTask.completed) {
            wx.showToast({
                title: '今日视频任务已完成',
                icon: 'none'
            });
            return;
        }

        if (videoTask.currentTimes >= videoTask.maxTimes) {
            wx.showToast({
                title: '今日观看次数已用完',
                icon: 'none'
            });
            return;
        }

      this.onShowAd()

        setTimeout(() => {
            wx.hideLoading();

            // 模拟视频观看完成
            videoTask.currentTimes += 1;

            // 检查是否完成任务
            if (videoTask.currentTimes >= videoTask.maxTimes) {
                videoTask.completed = true;
            }

            // 增加积分
            const earnedPoints = videoTask.points / videoTask.maxTimes; // 每次观看获得的积分
            const newPoints = this.data.points + earnedPoints;

            // 更新数据
            this.setData({
                taskList,
                points: newPoints
            });

            // 保存到本地
            this.saveTaskData();
            this.savePointsData();
            this.updateTaskDisplay();

            wx.showToast({
                title: `观看完成 +${earnedPoints}积分`,
                icon: 'success'
            });

            console.log('视频任务完成:', {
                currentTimes: videoTask.currentTimes,
                completed: videoTask.completed,
                points: newPoints
            });
        }, 2000);
    },

    // 处理签到按钮点击
    handleSign() {
        if (this.data.isSigned) {
            wx.showToast({
                title: '今日已签到',
                icon: 'none'
            });
            return;
        }

        // 模拟签到操作
        wx.showLoading({
            title: '签到中...',
        });

        setTimeout(() => {
            wx.hideLoading();

            // 计算签到奖励
            const signReward = this.data.signDays >= 7 ? 50 : 5;
            const newPoints = this.data.points + signReward;
            const newSignDays = this.data.signDays < 7 ? this.data.signDays + 1 : 1; // 7天后重新开始

            // 更新数据
            this.setData({
                isSigned: true,
                points: newPoints,
                signDays: newSignDays
            });

            // 保存到本地
            this.savePointsData();
            this.saveSignData();

            wx.showToast({
                title: `签到成功 +${signReward}积分`,
                icon: 'success'
            });

            console.log('签到完成:', {
                points: newPoints,
                signDays: newSignDays,
                reward: signReward
            });
        }, 1000);
    },

    // 处理返回按钮点击
    handleBack() {
        wx.navigateBack();
    },

    // 清除所有数据（调试用）
    clearAllData() {
        wx.removeStorageSync(this.STORAGE_KEYS.TASK_DATA);
        wx.removeStorageSync(this.STORAGE_KEYS.USER_POINTS);
        wx.removeStorageSync(this.STORAGE_KEYS.SIGN_DATA);
        wx.removeStorageSync(this.STORAGE_KEYS.LAST_UPDATE);

        wx.showToast({
            title: '数据已清除',
            icon: 'success'
        });

        // 重新初始化
        this.initTaskData();
    },

    // 分享给朋友
    onShareAppMessage: function () {
        // 分享时完成分享任务
        this.handleShare();

        return {
            title: '学法减分题库 - 完成助力任务得积分',
            path: '/pages/index/index?from=task_share',
            imageUrl: '/assets/share.png'
        };
    },

    // 分享到朋友圈
    onShareTimeline: function () {
        // 分享时完成分享任务
        this.handleShare();

        return {
            title: '学法减分题库 - 完成助力任务得积分',
            query: 'from=task_share',
            imageUrl: '/assets/share.png'
        };
    }
});